package yu.code.yurpc.bootstrap;

import yu.code.yurpc.RpcApplication;
import yu.code.yurpc.config.RegistryConfig;
import yu.code.yurpc.config.RpcConfig;
import yu.code.yurpc.model.ServiceMetaInfo;
import yu.code.yurpc.model.ServiceRegisterInfo;
import yu.code.yurpc.registry.LocalRegistry;
import yu.code.yurpc.registry.Registry;
import yu.code.yurpc.registry.RegistryFactory;
import yu.code.yurpc.server.VertxHttpServer;

import java.util.List;

/**
 * 服务提供者启动类（初始化）
 */
public class ProviderBootStrap {
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {
        //RPC 框架初始化
        RpcApplication.init();
        //注册服务到注册中心
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            //本地注册
            LocalRegistry.register(serviceRegisterInfo.getServiceName(), serviceRegisterInfo.getImplClass());
            //注册服务
            LocalRegistry.register(serviceRegisterInfo.getServiceName(), serviceRegisterInfo.getImplClass());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceRegisterInfo.getServiceName());
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceRegisterInfo.getServiceName()+"服务注册失败",e);
            }
        }
        //启动 TCP 服务
        VertxHttpServer vertxHttpServer = new VertxHttpServer();
        vertxHttpServer.start(8080);
    }
}
